
import { useResizeDetector } from 'react-resize-detector'
import React, { useEffect, useRef, useState } from 'react'
import { Context, useAxiosWebGet, useAxiosWebPost, ILoginOptions, ICurrentUser, IMenu, navigationTo } from '@sker/sdk';
import { message as antdMessage, notification as antdNotification, Modal } from 'antd';
import { BrowserHistory, createBrowserHistory } from 'history'
import { NavigationTo } from '@sker/sdk'
import { useServerData } from './server';
import { createRoot } from 'react-dom/client';
export const Layout: React.FC<React.PropsWithChildren<{}>> = ({ children }) => {
    const [serverData] = useServerData()
    const mainRef = useRef();
    const { width, height, ref } = useResizeDetector();
    const [Page, setPage] = useState<any>()
    const [currentUser, setCurrentUser] = useState<ICurrentUser>()
    const getHistory = () => {
        let adminHistory = Reflect.get(window, 'adminHistory')
        if (!adminHistory) {
            const history = createBrowserHistory()
            history.listen(async ({ location, action }) => {
                const page = await navigationTo(location.pathname)
                if (page) {
                    setPage(page)
                }
            })
            Reflect.set(window, 'adminHistory', history)
        }
        return Reflect.get(window, 'adminHistory')
    }
    const [history, setHistory] = useState<BrowserHistory>(getHistory())
    const loadScript = async (link: string, params: any = { t: Date.now() }, state: any = {}) => {
        const query = Object.keys(params).map(k => `${k}=${params[k]}`).join('&')
        history.push(`/${link.split('/').filter(it => !!it).join('/')}?${query}`, state)
    }
    const [navigate, setNavigate] = useState<NavigationTo>(() => loadScript)
    const { fetch: fetchMe } = useAxiosWebGet('imeepos/core/user/me')
    const { fetch: fetchLogin } = useAxiosWebPost('imeepos/core/user/login')
    const { fetch: fetchCaptch } = useAxiosWebGet('imeepos/core/user/captcha')
    const { fetch: fetchLogout } = useAxiosWebPost('imeepos/core/user/logout')
    const [message, contextMessage] = antdMessage.useMessage();
    const [notification, contextNotification] = antdNotification.useNotification()
    const [modal, contextModal] = Modal.useModal()
    const [fold, setFold] = useState<boolean>(false)
    const [menus, setMenus] = useState<IMenu[]>([])
    useEffect(() => {
        setHistory(getHistory())
        if (mainRef.current) {
            const root = Reflect.get(window, 'REACT_ROOT')
            if (!root) {
                Reflect.set(window, 'NGER', true)
                Reflect.set(window, 'ROUTER_OUTLET', mainRef.current)
                Reflect.set(window, 'REACT_ROOT', createRoot(mainRef.current))
            }
        }
    }, [])
    // 我的
    const me = async (auto: boolean = true) => {
        try {
            const res = await fetchMe()
            if (res?.success) {
                setCurrentUser(res.data)
            } else {
                if (auto) {
                    message.error(res.message)
                    localStorage.setItem('refrence', window.location.href)
                    window.location.href = serverData?.addon?.login_url || serverData?.login || '/imeepos/core/web/login'
                }
            }
        } catch (e) {
            if (auto) {
                localStorage.setItem('refrence', window.location.href)
                window.location.href = serverData?.addon?.login_url || serverData?.login || '/imeepos/core/web/login'
            }
        }
    }
    // 登录
    const login = async (options: ILoginOptions) => {
        const res = await fetchLogin(options)
        const { success, data } = res;
        if (success && message) {
            await message.success(res.message)
            const refrence = localStorage.getItem('refrence')
            localStorage.removeItem('refrence')
            localStorage.setItem('currentUser', JSON.stringify(res.data))
            window.location.href = refrence || data.welcome_link;
            return res;
        } else {
            await message?.error(res.message)
            return res;
        }
    }
    const logout = async () => {
        const res = await fetchLogout()
        if (res.success) {
            await message.success(`已成功退出登录`)
            localStorage.removeItem('currentUser')
            window.location.href = serverData?.addon?.login_url || serverData?.login || '/imeepos/core/web/login'
            return;
        } else {
            await message.error(res.message)
            return;
        }
    }
    const getPageSetting = async () => { }
    /**
     * 验证码
     */
    const captcha = async (width: number, height: number) => {
        const { data, hashkey } = await fetchCaptch({ width: `${width}`, height: `${height}` })
        return { data, hashkey }
    }
    return <div ref={ref} id="app-container">
        {contextMessage}
        {contextNotification}
        {contextModal}
        <Context.Provider value={{
            width, height, login, getPageSetting, captcha,
            currentUser, setCurrentUser, me,
            menus, setMenus, fold, setFold, logout, message, notification, modal,
            navigate, setNavigate, history
        }}>
            {Page && Page}
            {!Page && <div id="app-container" ref={mainRef}>
                {children}
            </div>}
        </Context.Provider>
    </div>;
}